import cTitle from "components/title";
import { Toast } from "vant";
import yzService from "components/ui_components/yz_service.vue";
export default {
  data() {
    return {
      storeId: "",
      iPnoneBottomBol: false, //是否是苹果手机
      posterImg: "",
      workTime: "", //营业日期
      posterShow: false, //海报弹窗
      consultShow: false, //咨询弹窗
      collectChecked: 0, //是否收藏
      storePage: 1,
      storeLastPage: 0,
      storeMore: false,
      addressDetail: "",
      couponStore: {},
      loveName: "", //爱心值别名
      pointName: "", //积分别名
      commercialTab: [
        {
          name: "到店优惠",
          status: 0
        },
        {
          name: "堂食点单",
          status: 1
        },
        {
          name: "打包自取",
          status: 2
        },
        {
          name: "外卖",
          status: 3
        }
      ],
      storeDetail: {}, //商户详情
      storeGoodsList: [],
      workWeek: [
        //显示选中的日期数组
        {
          title: "周一",
          value: "1"
        },
        {
          title: "周二",
          value: "2"
        },
        {
          title: "周三",
          value: "3"
        },
        {
          title: "周四",
          value: "4"
        },
        {
          title: "周五",
          value: "5"
        },
        {
          title: "周六",
          value: "6"
        },
        {
          title: "周日",
          value: "7"
        }
      ],
      latitude: "",
      longitude: "",
      //客服插件
      isMiniApp: window.isMiniprogram ? true : false,
      customerOpen: false, //客服弹窗开关
      serviceShow: false,
      serviceQRcode: "",
      serviceMobile: "",
      cservice: ""
    };
  },
  activated() {
    this.storeId = this.$route.query.storeId;
    this.storePage = 1;
    this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.longitude = p.lng;
        this.latitude = p.lat;
        this.storeDetails();
      })
      .catch(err => {
        console.log(err);
      });
    this.storeGoodsLists();
    this.storePoster();
    this.serviceDetail();
  },
  filters: {
    caitalize(value) {
      let v;
      if (typeof value === "number" && !isNaN(value)) {
        if (value >= 1000) {
          v = (value / 1000).toFixed(2) + "km";
        } else {
          v = value + "m";
        }
      } else {
        v = "0m";
      }
      return v;
    }
  },
  methods: {
    onBack() {
      if (window.history.length <= 1) {
        this.$router.push(this.fun.getUrl("home", {}));
      } else {
        this.$router.back();
      }
    },
    getiPnoneBottom() {
      let that = this;
      try {
        let value = wx.getStorageSync("iPhoneBottom");
        if (value) {
          that.setData({
            iPnoneBottomBol: true
          });
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    shareHint() {
      wx.showToast({
        icon: "none",
        title: "长按图片分享好友",
        duration: 3000
      });
    },
    saveImg() {
      //保存图片
      var image = new Image();
      //跨域会导致a标签在部分浏览器中会直接打开新标签页 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");

        // 生成一个a元素
        var a = document.createElement("a");
        // 创建一个单击事件
        var event = new MouseEvent("click");

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || "下载图片名称";
        // 将生成的URL设置为a.href属性
        a.href = url;

        // 触发a的单击事件
        a.dispatchEvent(event);
      };

      image.src = document.getElementById("picurl").src;
    },
    clickChat() {
      let setServicePlugin = this.fun.isTextEmpty(this.serviceMobile) && this.fun.isTextEmpty(this.serviceQRcode);
      if (this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        return this.$toast("抱歉，暂未设置客服信息");
      }
      if (!this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        //只设置了客服链接，直接跳转
        if (this.cservice && this.cservice.indexOf("chatWindow") >= 0) {
          window.location.href = this.cservice + "&goods_id=" + this.$route.params.id;
        } else {
          window.location.href = this.cservice;
        }
        return;
      }
      this.serviceShow = true;
    },
    storeGoodsLists() {
      let json = {
        basic_info: 1,
        store_id: Number(this.storeId),
        page: this.storePage,
        paginate: 3
      };
      $http.post("plugin.coupon-store.frontend.store.storeGoodsList", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            if (!this.storeLastPage) {
              this.storeLastPage = 0;
            }
            this.storeGoodsList = res.data;
            this.storeMore = true;
            this.storeLastPage = res.last_page;
            this.loveName = res.basic_info?.love;
            this.pointName =this.fun.getCustomTextLang('member_center.credit1','积分');
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    storeDetails() {
      let json = {
        store_id: Number(this.storeId),
        longitude: this.longitude,
        latitude: this.latitude
      };
      $http.post("plugin.coupon-store.frontend.store.storeDetail", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let addressDetail = `${res.city}${res.district}${res.street}${res.address}`,
              workWeek = res.work_week,
              workWeekData = this.workWeek,
              weekList = [];
            weekList = workWeekData.filter(item => workWeek.indexOf(item.value) > -1); //筛选选中的日期
            let workTimeTitle = `${weekList[0].title}至${weekList[weekList.length - 1].title}`;
            this.storeDetail = res;
            this.addressDetail = addressDetail;
            this.workTime = workTimeTitle;
            this.collectChecked = res.is_collection;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    onCollect() {
      this.collectChecked = this.collectChecked === 0 ? 1 : 0;
      let json = {
        store_id: this.storeId,
        status: this.collectChecked
      };
      $http.post("plugin.coupon-store.frontend.collection.storeCollect", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            Toast(response.msg);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    onCommercialTo() {
      //跳转商户信息
      this.$router.push(
        this.fun.getUrl(
          "commercial",
          {},
          {
            storeId: this.storeId
          }
        )
      );
    },
    programNav(event) {
      window.location.href = event;
    },
    goodsDetail(id) {
      this.$router.push(
        this.fun.getUrl(
          "goodsDetails",
          {},
          {
            goodsId: id
          }
        )
      );
    },
    phone() {
      window.location.href = "tel://" + this.storeDetail.store_mobile;
    },
    storePoster() {
      //海报信息设置
      let json = {
        store_id: this.storeId
      };
      $http.post("plugin.coupon-store.frontend.poster.storePoster", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.posterImg = res.url;
            // Toast(res.msg);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", { goods_id: this.goodsId }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    tapIndex() {
      //首页跳转
      this.$router.replace(this.fun.getUrl("home", {}, {}));
    },
    closePop() {
      this.serviceShow = false;
    },
    onClose() {
      this.posterShow = false;
      this.consultShow = false;
    },
    goodsMoreData() {
      this.goodsMore = false; // 防止多次请求分页数据
      if (this.storePage >= this.storeLastPage) {
        return;
      } else {
        this.storePage += 1;
        let json = {
          basic_info: 1,
          store_id: this.storeId,
          page: this.storePage,
          paginate: 3
        };
        $http.post("plugin.coupon-store.frontend.store.storeGoodsList", json, "正在获取").then(
          response => {
            if (response.result == 1) {
              let res = response.data;
              let list = res.data;
              this.goodsMore = true;
              this.storeGoodsList = [...this.storeGoodsList, ...list];
              this.storeLastPage = res.last_page;
            } else {
              this.goodsPage -= 1;
              this.$dialog.alert({ message: response.msg });
            }
          },
          function(response) {
            // console.log(response);
            // error callback
          }
        );
      }
    },
    navigation(latitude, longitude) {
      let point = this.fun.bd_decrypt(longitude, latitude);
      this.fun.goToWXAdress(point, this.storeDetail.store_name, this.storeDetail.address);
    },
    onConsultClose() {
      this.consultShow = false;
    },
    onConsult() {
      this.consultShow = true;
    },
    onPosterClick() {
      this.posterShow = true;
      this.storePoster();
    }
  },
  components: {
    cTitle,
    yzService
  }
};
